
package JET.Centers.Scripts;

import JET.Centers.ControlCenter;
import JET.physics.interfaces.ProjectTreeNode;
import JET.physics.interfaces.SceneTreeNode;
import javax.script.CompiledScript;
import javax.script.Compilable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 *
 * @author 057Ry
 */
public class MyScript implements ProjectTreeNode {

    protected String            script;
    protected String            name;
    protected CompiledScript    compiledScript;
    protected boolean           compiled;
    
    // States if this script is opened in CPScriptEditor
    protected boolean           edited;

    public MyScript(String name) {
        this.name = name;
        this.script = "";
        compiled = false;
        edited = false;
    }
    
    public MyScript(String name, String script) {
        this.name = name;
        this.script = script;
        compiled = false;
        edited = false;
    }

    public void setScript(String script) {
        //if (!script.equals(this.script)) {
            this.script = script;
            compiled = false;
        //}
    }
    
    public String getScript() {
        return script;
    }

    public boolean isCompiled() {
        return compiled;
    }

    public void setEdited(boolean e) {
        this.edited = e;
    }
    public boolean isEdited() {
        return edited;
    }

    public void compile(ScriptEngine engine, ControlCenter CC) {
        try {
            
            Compilable compilingEngine = (Compilable) engine;
            compiledScript = compilingEngine.compile(script);
            compiled = true;
            
        } catch (ScriptException ex) {
            CC.GUIC.printlnToOutput("[Ex] Exception while compiling script '"+name+"'");
            CC.GUIC.printlnToOutput(ex.getMessage());
            ex.printStackTrace();
        }
    }

    public void execute(ScriptEngine engine, ControlCenter CC) {
        try {
            if (compiled)
                compiledScript.eval(engine.getContext());
        } catch (ScriptException ex) {
            CC.GUIC.printlnToOutput("[Ex] Exception while executing script '"+name+"'");
            CC.GUIC.printlnToOutput(ex.getMessage());
            ex.printStackTrace();
        }
    }

    public String toString() {
        return name;
    }
    public String getName() {
        return name;
    }

    public ProjectTreeNode getChild(int index) {
        return null;
    }

    public int getChildCount() {
        return 0;
    }

    public boolean isLeaf() {
        return true;
    }

    public int getIndexOfChild(Object child) {
        return -1;
    }

    public void resetNodeValue(Object o) {}
}